const userAgent = navigator.userAgent;
const browserVersion = parseInt(userAgent.match(/Chrome\/(\d+)/)[1], 10);

// 监听来自 content.js 的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.action === "getBrowserVersion") {
    sendResponse({ version: browserVersion });
  }
});

//开侧边栏
// chrome.action.onClicked.addListener((tab) => {
//   console.log('打开侧边栏！')
//   chrome.sidePanel.open({ windowId: tab.windowId });
// })

chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
  if (changeInfo.status === 'complete') {
    // 页面加载完成，注入content.js
    chrome.scripting.executeScript({
      target: { tabId: tabId },
      files: ['content.js']
    });
  }
});

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  // 查询当前激活页面tab，掉用content.js获取dom,结果返回给app.vue
  if (request.action === 'getDOM4Service') {
    console.log("service-worker getDOM4Service")
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      console.log("service-worker chrome.tabs.query")
      if (tabs[0]) {
        console.log("tabs[0].id=", tabs[0].id);
        chrome.tabs.sendMessage(tabs[0].id, { action: 'getDOM' }, (response) => {
          console.log("service-worker chrome.tabs.sendMessage")
          sendResponse(response);
        });
      }
    });
    return true;
  }
  // 监听小宇悬浮按钮
  if (request.xuanfu_switch !== undefined) {
    console.log("service-worker xuanfu_switch")
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { xuanfu_switch_content: request.xuanfu_switch }, (response) => {
        sendResponse(response);
      });
    });
  }

  // 监听小宇选取按钮
  if (request.xuanqu_switch !== undefined) {
    console.log("service-worker xuanqu_switch")
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { xuanqu_switch_content: request.xuanqu_switch }, (response) => {
        sendResponse(response);
      });
    });
  }

  // 监听小宇选取按钮
  if (request.selectWindowType !== undefined) {
    console.log("service-worker selectWindowType")
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      chrome.tabs.sendMessage(tabs[0].id, { selectWindowType_content: request.selectWindowType }, (response) => {
        sendResponse(response);
      });
    });
  }

  // 监听触发侧边栏
  if (request.action === 'openSidebar') {
    console.log('打开侧边栏！');
    chrome.sidePanel.open({ windowId: sender.tab.windowId });
  }
});



